<template>
  <nav class="navbar is-white is-rounded">
    <div class="container">
      <div class="navbar-menu">
        <div class="navbar-start">
            <a
            class="navbar-item"
      v-for="(period, index) in periods" :key="index"
        @click="setPeriod(period)"
        :class="[period === selectedPeriod ? 'is-active' : '']"
        data-test="period"
        >{{ period }}</a
      >
        </div>
        <div class="navbar-end">
           <div class="navbar-item mr-3">
               <router-link class="button is-primary is-alt" to="/posts/new">添加博客</router-link>
           </div>
        </div>
      </div>
    </div>
  </nav>
  <TimelinePost :post="post" v-for="post in posts" :key="post.id" />
   
</template>
<script lang="ts">
import { computed, defineComponent, ref } from "vue";
import { Period,Post } from "@/types";
import { useStore } from "@/store";
import moment from "moment";
import TimelinePost from "./TimelinePost.vue"; // @ is an alias to /src
// const delay=(ms:number)=>new Promise((res=>setTimeout(res,ms)))



export default defineComponent({
  name: "Timelne",
  components:{
    TimelinePost
  },
 async setup() {
    const periods: Period[] = ["今天", "本周", "本月"];
    const selectedPeriod = ref<Period>("今天");
    const store=useStore()
    if(!store.getState().posts.loaded){
      await store.fetchPosts()
    }
    let allPost=store.getState().posts.ids.reduce<Post[]>((acc,id)=>{
      const post=store.getState().posts.all[id]
      return acc.concat(post)
    },[])
    // await delay(2000)
    // tab 切换
    const setPeriod = (period: Period) => {
      selectedPeriod.value = period;
    };
    const posts = computed(() => {
     return allPost.filter((post) => {
        if (
          selectedPeriod.value === "今天" &&
          post.created.isAfter(moment().subtract(1, "day"))
        )
          return true;
        if (
          selectedPeriod.value === "本周" &&
          post.created.isAfter(moment().subtract(7, "day"))
        )
          return true;
        if (
          selectedPeriod.value === "本月" &&
          post.created.isAfter(moment().subtract(1, "month"))
        )
          return true;
        return false;
      });
    });

    return { periods, selectedPeriod, setPeriod, posts };
  },
});
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
